<script setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {exportExcel} from '../utils/file'
import request from '../utils/request'

const tableData = ref([]) // 导入的原始数据
const uploadRef = ref(null)
const isRunning = ref(false)
const progress = ref(0) // 进度百分比
const progressText = ref('') // 进度文本
const processingInfo = ref('') // 处理信息
let stopFlag = false
let progressTimer = null // 进度轮询定时器

// 上传成功回调
function handleUploadSuccess(response, file, fileList) {
  if (response && response.message === '上传成功') {
    ElMessage.success('上传成功，文件已保存到服务器')
    // 将返回的文件信息添加到tableData，解码防止中文乱码
    tableData.value = [{
      id: tableData.value.length + 1,
      filename: decodeURIComponent(response.filename),
      path: decodeURIComponent(response.path),
      status: response.message
    }]
  } else {
    ElMessage.error('上传失败')
  }
}

// 轮询进度
function startProgressPolling() {
  progressTimer = setInterval(async () => {
    try {
      const res = await request.get('/api/progress')
      if (res.data.code === 200) {
        const data = res.data.data
        if (data.total > 0) {
          progress.value = Math.round((data.finished / data.total) * 100)
          progressText.value = data.message || '处理中...'
          processingInfo.value = `成功: ${data.success}, 失败: ${data.failed}, 进度: ${data.finished}/${data.total}`
        }
        
        // 如果处理完成，停止轮询
        if (!data.isProcessing && data.finished > 0) {
          stopProgressPolling()
          isRunning.value = false

          // 新增：将结果文件路径显示到结果信息
          if (tableData.value.length > 0 && data.message) {
            tableData.value[0].message = data.message
          }

          if (data.failed === 0) {
            ElMessage.success(`处理完成！成功: ${data.success}, 失败: ${data.failed}`)
          } else {
            ElMessage.warning(`处理完成！成功: ${data.success}, 失败: ${data.failed}`)
          }
        }
      }
    } catch (error) {
      console.error('获取进度失败:', error)
    }
  }, 1000) // 每秒轮询一次
}

// 停止轮询
function stopProgressPolling() {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
}

async function handleBatchRun() {
  if (tableData.value.length === 0) {
    ElMessage.warning('请先导入数据')
    return
  }
  isRunning.value = true
  stopFlag = false
  progress.value = 0
  progressText.value = '准备开始处理...'
  processingInfo.value = ''
  
  try {
    const res = await request.post('/api/batchRun', [tableData.value[0]])
    if (res.data.code === 200) {
      ElMessage.success('任务已开始，正在处理中...')
      // 开始轮询进度
      startProgressPolling()
    } else {
      progress.value = 0
      progressText.value = '处理失败'
      processingInfo.value = res.data.message
      isRunning.value = false
      ElMessage.error('运行失败: ' + res.data.message)
    }
  } catch (err) {
    progress.value = 0
    progressText.value = '处理失败'
    processingInfo.value = err.message || '网络请求失败'
    isRunning.value = false
    ElMessage.error('运行失败: ' + err.message)
  }
}

function handleStop() {
  stopFlag = true
  isRunning.value = false
  progress.value = 0
  progressText.value = '已终止'
  processingInfo.value = ''
  stopProgressPolling()
  ElMessage.info('已终止执行')
}

function handleExportTemplate() {
// 定义表头
  const header = ['序号', '标题', '作者', '播放量', '点赞', '投币', '收藏', '转发', '评论', '发布时间', '视频链接']
  // 模板数据（可为空或只留一行空数据）
  const data = [
    {
      '序号': '',
      '标题': '',
      '作者': '',
      '播放量': '',
      '点赞': '',
      '投币': '',
      '收藏': '',
      '转发': '',
      '评论': '',
      '发布时间': '',
      '视频链接': ''
    }
  ]
  // 导出
  exportExcel(data, 'bilibili模板.xlsx', header)
}
</script>

<template>
  <div class="bili-table-wrapper">
    <!-- 顶部：导入Excel -->
    <div class="bili-table-toolbar">
      <el-button size="large" style="margin-right: 12px;">blibli</el-button>
      <el-upload
          ref="uploadRef"
          :show-file-list="false"
          :auto-upload="true"
          accept=".xlsx"
          :action="request.defaults.baseURL + '/api/file/uploadExcel'"
          :on-success="handleUploadSuccess"
          style="display: inline-block;"
      >
        <el-button type="primary" size="large">导入Excel</el-button>
      </el-upload>
      <el-button type="info" size="large" @click="handleExportTemplate" style="margin-left: 12px;">导出模板</el-button>
    </div>

    <!-- 中部：执行/终止按钮 -->
    <div class="bili-table-actions">
      <el-button type="success" size="large" @click="handleBatchRun" :disabled="isRunning || tableData.length === 0">
        执行
      </el-button>
      <el-button type="danger" size="large" @click="handleStop" :disabled="!isRunning">终止</el-button>
    </div>

    <!-- 进度条 -->
    <div v-if="isRunning || progress > 0" class="progress-section">
      <el-progress 
        :percentage="progress" 
        :status="progress === 100 ? 'success' : 'active'"
        :stroke-width="8"
        :show-text="false"
      />
      <div class="progress-info">
        <span class="progress-text">{{ progressText }}</span>
        <span v-if="processingInfo" class="processing-info">{{ processingInfo }}</span>
      </div>
    </div>

    <!-- 底部：执行结果展示 -->
    <div class="bili-table-result">
      <el-table
          :data="tableData"
          class="bili-table"
          :border="true"
          empty-text="暂无执行结果，请先导入并执行"
      >
        <el-table-column prop="id" label="序号" width="70"/>
        <el-table-column prop="filename" label="文件名" min-width="180"/>
        <el-table-column prop="path" label="路径" min-width="120"/>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === '上传成功'" type="success">上传成功</el-tag>
            <el-tag v-else type="danger">上传失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="结果信息" min-width="180"/>
      </el-table>
    </div>
  </div>
</template>

<style scoped>
.bili-table-wrapper {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 4px 24px rgba(34, 34, 59, 0.08);
  padding: 40px 40px 32px 40px;
  margin: 40px auto;
  max-width: 1100px;
}

.bili-table-toolbar {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 32px;
}

.bili-table-actions {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 32px;
}

.progress-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}
.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}
.progress-text {
  font-weight: 500;
  color: #333;
}
.processing-info {
  font-size: 14px;
  color: #666;
}

.bili-table-result {
  margin-top: 12px;
}

.bili-table {
  border-radius: 10px;
  overflow: hidden;
  font-size: 16px;
}
</style>